<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @submit.native.prevent
      v-if="hasAuth('sys:user:find')"
    >
      <el-form-item label="选择部门:">
        <el-select
          v-model="formInline.departmentId"
          placeholder="请选择部门"
          @change="getUserList"
        >
          <el-option label="所有部门" :value="null"> </el-option>
          <el-option
            v-for="department in departmentList"
            :label="department.name"
            :value="department.id"
            :key="department.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名:">
        <el-input
          v-model="formInline.name"
          @keyup.enter.native="findByName"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item v-if="hasAuth('sys:user:find')">
        <el-button type="primary" round @click="findByName">查询</el-button>
      </el-form-item>
      <el-form-item v-if="hasAuth('sys:user:add')">
        <el-button type="success" round @click="addUserBtn">新增</el-button>
      </el-form-item>
      <el-form-item v-if="hasAuth('sys:user:del')">
        <el-popconfirm title="确定删除吗？" @confirm="delUserBtn(null)">
          <el-button
            type="danger"
            round
            slot="reference"
            :disabled="allDelStatus"
            v-if="hasAuth('sys:user:del')"
            >批量删除</el-button
          >
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table
      :data="userList"
      style="width: 100%"
      :max-height="tableHeight"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"> </el-table-column>
      <!-- <el-table-column prop="id" label="用户编号"> </el-table-column> -->
      <el-table-column prop="userName" label="用户名"> </el-table-column>
      <el-table-column prop="name" label="姓名"> </el-table-column>
      <el-table-column prop="sex" label="性别">
        <template slot-scope="scope">
          <div v-if="scope.row.sex === 0">女</div>
          <div v-if="scope.row.sex === 1">男</div>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码"> </el-table-column>
      <el-table-column prop="departmentName" label="所属部门">
      </el-table-column>
      <el-table-column prop="positionName" label="职位">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.positionName">{{
            scope.row.positionName
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roleCode" label="角色" width="250">
        <template slot-scope="scope">
          <template v-for="item in scope.row.roles">
            <el-tag size="small" :key="item.roleCode" v-if="item.roleName">{{
              item.roleName
            }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column prop="updateTime" label="更新时间"> </el-table-column> -->
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status" size="small" type="success"
            >正常</el-tag
          >
          <el-tag v-if="!scope.row.status" size="small" type="danger"
            >禁用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        v-if="hasAuth('sys:user:edit') || hasAuth('sys:user:del')"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="departmentHandle(scope.row.id, scope.row.departmentId)"
            v-if="hasAuth('sys:user:department')"
            >分配部门</el-button
          >
          <el-divider
            direction="vertical"
            v-if="
              hasAuth('sys:user:position') && hasAuth('sys:user:department')
            "
          ></el-divider>
          <el-button
            type="text"
            @click="positionHandle(scope.row.id, scope.row.positionId)"
            v-if="hasAuth('sys:user:position')"
            >分配职位</el-button
          >
          <el-divider
            direction="vertical"
            v-if="hasAuth('sys:user:role') && hasAuth('sys:user:position')"
          ></el-divider>
          <el-button
            type="text"
            @click="roleHandle(scope.row.id, scope.row.roles)"
            v-if="hasAuth('sys:user:role')"
            >分配角色</el-button
          >
          <el-divider
            direction="vertical"
            v-if="hasAuth('sys:user:role') && hasAuth('sys:user:repass')"
          ></el-divider>
          <el-button
            type="text"
            @click="repassHandle(scope.row.id, scope.row.userName)"
            v-if="hasAuth('sys:user:repass')"
            >重置密码</el-button
          >
          <el-divider
            direction="vertical"
            v-if="hasAuth('sys:user:repass') && hasAuth('sys:user:edit')"
          ></el-divider>
          <el-button
            type="text"
            @click="editUserBtn(scope.row.id)"
            v-if="hasAuth('sys:user:edit')"
            >编辑</el-button
          >
          <el-divider
            direction="vertical"
            v-if="hasAuth('sys:user:edit') && hasAuth('sys:user:del')"
          ></el-divider>
          <el-popconfirm
            title="确定删除吗？"
            @confirm="delUserBtn(scope.row.id)"
          >
            <el-button
              slot="reference"
              type="text"
              v-if="hasAuth('sys:user:del')"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="current"
      :page-sizes="[10, 15, 20, 50]"
      :page-size="size"
      :total="total"
    >
    </el-pagination>
    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="600px"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editForm"
        label-position="left"
        label-width="100px"
        class="demo-editForm"
      >
        <el-form-item v-if="editForm.id < 0" label="用户名" prop="userName">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="btnGroup">
          <el-button
            type="primary"
            @click="submitForm('editForm')"
            style="float: right; margin-left: 15px"
            >确认</el-button
          >
          <el-button @click="handleClose" style="float: right">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogFormVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="roleForm" ref="roleForm">
        <el-tree
          :data="roleTreeData"
          show-checkbox
          ref="roleTree"
          node-key="id"
          :default-expand-all="true"
          :props="defaultProps"
        >
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitRoleForm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配部门对话框 -->
    <el-dialog
      title="分配部门"
      :visible.sync="departmentDialogFormVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="departmentForm" ref="departmentForm">
        <el-form-item label="选择部门：">
          <el-select
            v-model="departmentForm.departmentId"
            placeholder="请选择部门"
          >
            <el-option label="暂无分配" :value="null"> </el-option>
            <el-option
              v-for="department in departmentList"
              :label="department.name"
              :value="department.id"
              :key="department.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitDepartmentForm()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 分配职位对话框 -->
    <el-dialog
      title="分配职位"
      :visible.sync="positionFormVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="positionForm" ref="positionForm">
        <el-form-item label="选择职位：">
          <el-select v-model="positionForm.positionId" placeholder="请选择职位">
            <el-option label="暂无分配" :value="null"> </el-option>
            <el-option
              v-for="position in positionList"
              :label="position.name"
              :value="position.id"
              :key="position.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitPositionForm()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "User",
  data() {
    return {
      current: 1,
      size: 10,
      total: 0,
      tableHeight: 600,
      allDelStatus: true,
      dialogFormVisible: false,
      dialogTitle: "",
      roleDialogFormVisible: false,
      roleForm: {},
      roleTreeData: [],
      defaultProps: { children: "children", label: "roleName" },
      departmentDialogFormVisible: false,
      positionFormVisible: false,
      departmentForm: {},
      positionForm: {},
      userList: [],
      departmentList: [],
      positionList: [],
      multipleSelection: [],
      formInline: {
        name: "",
        departmentId: null,
      },
      editForm: {
        id: -1,
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },

          {
            min: 5,
            max: 11,
            message: "长度在 5 到 11 个字符",
            trigger: "blur",
          },
          {
            pattern: /^[a-zA-Z0-9_-]{5,11}$/,
            message: "只能包含小写字符，数字或特殊符号“ _-”",
            trigger: "blur",
          },
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[34578]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        departmentId: [
          { required: true, message: "请选择部门", trigger: "change" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
      },
    };
  },
  // computed:{
  //   userList:{
  //     get(){
  //       return this.newUserList
  //     }
  //   }
  // },
  methods: {
    findByName() {
      this.current = 1;
      this.getUserList();
    },
    getUserInfoByUserId(id) {
      this.$axios.get("/user/info/" + id).then((res) => {
        this.editForm = res.data.data;
      });
    },
    editUserBtn(id) {
      this.dialogTitle = "编辑用户";
      this.getDepartmentList();
      this.getUserInfoByUserId(id);
      this.dialogFormVisible = true;
    },
    handleSizeChange(val) {
      this.size = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getUserList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.allDelStatus = val.length == 0;
      // console.log(this.multipleSelection);
    },
    handleClose() {
      this.dialogFormVisible = false;
      this.roleDialogFormVisible = false;
      this.departmentDialogFormVisible = false;
      this.positionFormVisible = false;
    },
    addUserBtn() {
      this.dialogTitle = "新增用户";
      this.editForm = { id: -1 };
      this.dialogFormVisible = true;
    },
    delUserBtn(id) {
      // console.log(id);
      var ids = [];
      if (id) {
        ids.push(id);
      } else {
        this.multipleSelection.forEach((row) => {
          ids.push(row.id);
        });
      }
      // console.log("ids:" + ids);
      this.$axios.post("/user/remove", ids).then((res) => {
        this.$message({
          showClose: true,
          type: "success",
          message: "删除成功!",
          onClose: () => {
            this.getUserList();
          },
        });
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editForm.id < 0) {
            this.$axios.post("/user/create", this.editForm).then((res) => {
              this.$message({
                showClose: true,
                type: "success",
                message: "新增成功!",
                onClose: () => {
                  this.getUserList();
                },
              });
              this.handleClose();
            });
          } else {
            console.log(this.editForm);
            this.$axios.post("/user/update", this.editForm).then((res) => {
              this.$message({
                showClose: true,
                type: "success",
                message: "修改成功!",
                onClose: () => {
                  this.getUserList();
                },
              });
              this.handleClose();
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getDepartmentList() {
      this.$axios.get("/department/list").then((res) => {
        this.departmentList = res.data.data;
      });
    },
    getPositionList() {
      this.$axios.get("/position/list").then((res) => {
        this.positionList = res.data.data;
      });
    },
    async getUserList() {
      await this.$axios
        .get("/user/page", {
          params: {
            name: this.formInline.name,
            departmentId: this.formInline.departmentId,
            current: this.current,
            size: this.size,
          },
        })
        .then((res) => {
          this.userList = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    roleHandle(id, roles) {
      console.log(roles);
      var roleIds = [];
      roles.forEach((role) => {
        roleIds.push(role.id);
      });
      this.roleForm = { userId: id };
      this.$axios.get("/role/list").then((res) => {
        this.roleTreeData = res.data.data;
        this.$refs.roleTree.setCheckedKeys(roleIds);
      });
      this.roleDialogFormVisible = true;
    },
    departmentHandle(id, departmentId) {
      this.departmentForm = { userId: id, departmentId: departmentId };
      this.departmentDialogFormVisible = true;
    },
    positionHandle(id, positionId) {
      this.positionForm = {
        id: id,
        positionId: positionId ? positionId : null,
      };
      this.getPositionList();
      this.positionFormVisible = true;
    },
    submitRoleForm(formName) {
      var roleIds = [];
      roleIds = this.$refs.roleTree.getCheckedKeys();
      this.$axios
        .post("/user/userRole/" + this.roleForm.userId, roleIds)
        .then((res) => {
          this.$message({
            showClose: true,
            message: res.data.message,
            type: "success",
            onClose: () => {
              this.getUserList();
            },
          });
          this.roleDialogFormVisible = false;
        });
    },
    submitDepartmentForm() {
      this.$axios
        .post("/user/userDepartment", this.departmentForm)
        .then((res) => {
          this.$message({
            showClose: true,
            message: res.data.message,
            type: "success",
            onClose: () => {
              this.getUserList();
            },
          });
          this.departmentDialogFormVisible = false;
        });
    },
    submitPositionForm() {
      this.$axios.post("/user/userPosition", this.positionForm).then((res) => {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: "success",
          onClose: () => {
            this.getUserList();
          },
        });
        this.positionFormVisible = false;
      });
    },
    repassHandle(userId, userName) {
      this.$confirm("将重置用户【" + userName + "】的密码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios.post("/user/repass", userId).then((res) => {
          this.$message({
            showClose: true,
            message: res.data.message,
            type: "success",
            onClose: () => {},
          });
        });
      });
    },
  },
  created() {
    if (this.hasAuth("sys:user:find")) {
      var that = this
      this.getUserList().then(function () {
        that.getDepartmentList();
      });
    }
  },
  // mounted() {
  //   this.timer = window.setInterval(() => {
  //     setTimeout(() => {
  //       if (
  //         !this.dialogFormVisible &&
  //         this.allDelStatus &&
  //         this.hasAuth("sys:user:find")
  //       ) {
  //         this.getUserList();
  //       }
  //     }, 0);
  //   }, 5000);
  // },
  // destroyed() {
  //   window.clearInterval(this.timer);
  // },
};
</script>
<style scoped>
.demo-form-inline {
  float: right;
}
.demo-editForm {
  margin: 0px 30px;
}
.btnGroup {
  margin-top: 50px;
}
</style>